/**
 * Created by waterworld on 16-5-22.
 */
var qiniuUtil = module.exports;

var fs = require('fs');
var url = require('url');
var http = require('http');
var P=require('bluebird');
var qiniu = require("qiniu");
var util = require('util');
var qiniuConfig = require('../../../shared/config/qiniu');
//需要填写你的 Access Key 和 Secret Key
qiniu.conf.ACCESS_KEY = qiniuConfig.ACCESS_KEY;
qiniu.conf.SECRET_KEY = qiniuConfig.SECRET_KEY;
var phttp= P.promisifyAll(http);
var Et = require('events').EventEmitter;

//要上传的空间
var bucket = qiniuConfig.bucket;

//上传到七牛后保存的文件名
//key = 'my-nodejs-logo.png';

//构建上传策略函数
function uptoken(bucket, key) {
    var putPolicy = new qiniu.rs.PutPolicy(bucket+":"+key);
    return putPolicy.token();
}
qiniuUtil.downloadDir='private/download/';
//http://o6snbm1ny.bkt.clouddn.com/8_20131204160859.jpg
qiniuUtil.downFile=function(fileUrl,cb)
{
    var options = {
        host: url.parse(fileUrl).host,
        port: 80,
        path: url.parse(fileUrl).pathname
    };
    var self=this;
    var file_name = decodeURI(url.parse(fileUrl).pathname.split('/').pop());
    var filePath=this.downloadDir + file_name;
    var file = fs.createWriteStream(filePath);
    http.get(options, function(res){
        res.on('data', function(data) {
            file.write(data);
        }).on('end', function(){
            file.end();
            //cb(filePath);
            cb=filePath;
            console.log(file_name + ' downloaded to ' + self.downloadDir);
            return filePath;
        });
    });
}

qiniuUtil.pdownFile= P.coroutine(function*(fileUrl)
{   var options = {
        host: url.parse(fileUrl).host,
        port: 80,
        path: url.parse(fileUrl).pathname+'?'+new Date().getTime()
    };
    var self=this;
    var file_name = decodeURI(url.parse(fileUrl).pathname.split('/').pop());
    var filePath=this.downloadDir + file_name;//eg:private/download/8_iconList.txt
    var file = fs.createWriteStream(filePath);
    var    Ticker=function(){};
    util.inherits(Ticker,Et);
    var ticker = new Ticker();
    var loaded = new Promise(function(resolve, reject) {ticker.on("tick", resolve);});

    //catch 捕获回调的第一个参数，通常情况下是err参数，这里是res
    http.get(options, function(res){
        res.on('data', function(data) {
            file.write(data);
        }).on('end', function(){
            file.end();
            ticker.emit('tick',filePath);

        });
    }).on('error', function(err){
        console.log('http donloadfile error',err);
        ticker.emit('tick',filePath);
    });
    yield loaded.then(function(path){ });
    return filePath;
});

qiniuUtil.pdownFileByName= P.coroutine(function*(fileName)
{    return yield this.pdownFile(qiniuConfig.url+'/'+fileName);
});
qiniuUtil.downFileAsync= P.promisify(qiniuUtil.downFile);

//构造上传函数
//上传到七牛后保存的文件名
//fileKey = 'my-nodejs-logo.png';
qiniuUtil.uploadFile=function (fileKey, localFile,cb) {
    var token = uptoken(bucket, fileKey);
    var extra = new qiniu.io.PutExtra();
    qiniu.io.putFile(token, fileKey, localFile, extra, function(err, ret) {
        if(!err) {
            // 上传成功， 处理返回值
            cb(err,ret);
            // 上传成功， 处理返回值
           // console.log(ret.hash, ret.key, ret.persistentId);
        } else {
            // 上传失败， 处理返回代码
            cb(err,null);
            console.log(err);
        }
    });
}

qiniuUtil.uploadFileAsync= P.promisify(qiniuUtil.uploadFile);

qiniuUtil.addUrltoUserlist=function(userName,fileName,cb)
{

}

qiniuUtil.deleteUserlistUrl=function(userName,id,cb)
{

}
//调用uploadFile上传
console.log('quniuUpload load end....');